/*
 * @(#)RetrieveRequest.java
 * Date 2013-10-21
 * Version 1.0
 * Author Jim Horner
 * Copyright (c)2012
 */


package us.hornerscorners.lamppost.xca.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import ihe.iti.xds_b._2007.RetrieveDocumentSetRequestType.DocumentRequest;

import us.hornerscorners.lamppost.exception.ServiceActionError;

import us.hornerscorners.lamppost.repository.client.IRepositoryClient;


/**
 * Class description
 *
 *
 * @version        v1.0, 2013-10-21
 * @author         Jim Horner
 */
public class RetrieveRequest {

    /** Field description */
    private final List<ServiceActionError> errors;

    /** Field description */
    private final Map<String, RepositoryRequest> requestsMap;

    /**
     * Constructs ...
     *
     *
     * @param clients
     */
    public RetrieveRequest(IRepositoryClients clients) {

        super();
        this.errors = new ArrayList<>();
        this.requestsMap = new HashMap<>();

        for (IRepositoryClient client : clients.findAll()) {

            this.requestsMap.put(client.getClientId(), new RepositoryRequest(client));
        }
    }

    /**
     * Method description
     *
     *
     * @param error
     */
    public void addError(ServiceActionError error) {

        this.errors.add(error);
    }

    /**
     * Method description
     *
     *
     * @param id
     * @param request
     */
    public void addRequest(String id, DocumentRequest request) {

        RepositoryRequest repRequest = this.requestsMap.get(id);

        if (repRequest == null) {

            // you can't handle a null
            String msg = String.format("Repository [%s] is unknown.", id);

            throw new IllegalArgumentException(msg);
        }

        repRequest.add(request);
    }

    /**
     * Method description
     *
     *
     * @return
     */
    public ServiceActionError[] getErrors() {

        return this.errors.toArray(new ServiceActionError[this.errors.size()]);
    }

    /**
     * Method description
     *
     *
     *
     * @return
     */
    public RepositoryRequest[] getRepositoryRequests() {

        List<RepositoryRequest> result = new ArrayList<>();
        
        for (RepositoryRequest request : this.requestsMap.values()) {
            
            if (request.hasDocumentReqeusts()) {
                
                result.add(request);
            } 
        }

        return result.toArray(new RepositoryRequest[result.size()]);
    }

    /**
     * Method description
     *
     *
     * @return
     */
    public boolean hasErrors() {

        return (this.errors.isEmpty() == false);
    }
}
